package com.booksystem.campuslibrarymanagementsystem.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    private JwtUtil() {
    }
    private static final long EXPIRATION_TIME = 86400000; // 1天的过期时间
    private static final Key SIGNING_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256); // 使用静态密钥，确保签发和验证使用相同的密钥


    //获取token
    private static String generateToken(String identity, String account) {
        // 构建Token的payload部分
        Map<String, Object> claims = new HashMap<>();
        claims.put("identity", identity);
        claims.put("account", account);

        // 生成JWT Token
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SIGNING_KEY, SignatureAlgorithm.HS256)
                .compact();
    }

    //解析token
    private static Map<String, Object> parseToken(String token) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(SIGNING_KEY) // 使用之前定义的SIGNING_KEY
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            System.out.println("Token解析失败：" + e.getMessage());
            return null;
        }
    }

    public static String tokenGet(String identity, String account) {
        return generateToken(identity, account);
    }

    public static Map<String, Object> tokenPre(String token) {
        return parseToken(token);
    }

}